package com.chunxuan.langquan;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.widget.FrameLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.chunxuan.langquan.base.BaseResult2;
import com.chunxuan.langquan.base.Config;
import com.chunxuan.langquan.base.Global;
import com.chunxuan.langquan.dao.bean.EventModel;
import com.chunxuan.langquan.dao.bean.VersionInfo;
import com.chunxuan.langquan.dao.http.APIRetrofit;
import com.chunxuan.langquan.support.util.ActiviceCollector;
import com.chunxuan.langquan.support.util.Logg;
import com.chunxuan.langquan.support.util.PackageUtils;
import com.chunxuan.langquan.support.widget.BottomNavigationViewEx;
import com.chunxuan.langquan.ui.activity.GuidActivity;
import com.chunxuan.langquan.ui.fragment.Home1Fragment;
import com.chunxuan.langquan.ui.fragment.Home2Fragment;
import com.chunxuan.langquan.ui.fragment.Home3Fragment;
import com.chunxuan.langquan.ui.fragment.Home4Fragment;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.kongzue.kongzueupdatesdk.v3.UpdateUtil;
import com.ruitu.arad.Arad;
import com.ruitu.arad.api.RxUtil;
import com.ruitu.arad.base.BaseActivity;
import com.ruitu.arad.support.view.NoScrollViewPager;
import com.ruitu.arad.util.AppUtils;
import com.ruitu.arad.util.ScreenUtils;
import com.ruitu.arad.util.SizeUtils;
import com.ruitu.arad.util.ToastUtils;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;


public class MainActivity extends BaseActivity {

    private BottomNavigationViewEx bnve;
    private NoScrollViewPager vp;
    private int mPreTabIndex = 0;

    private VpAdapter adapter;
    private int guidId=0;
    private UpdateUtil updateUtil;
    @Override
    protected int getLayoutRes() {
        return R.layout.activity_main;
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActiviceCollector.addActivity(this);
        Intent intent=getIntent();
        if(intent!=null){
            guidId=intent.getIntExtra("guid_id",0);
        }
        bnve = findViewById(R.id.bnve);
        vp = findViewById(R.id.vp);

//        vp.setOffscreenPageLimit(9);
        vp.setScanScroll(false);

        bnve.enableAnimation(false);
        bnve.enableShiftingMode(false);
        bnve.enableItemShiftingMode(false);

        bnve.setIconsMarginTop(SizeUtils.dp2px(10));
        bnve.setIconSize(23, 23);
        bnve.setTextSize(10);
        bnve.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                for (int i = 0; i < bnve.getMenu().size(); i++) {
                    MenuItem menu = bnve.getMenu().getItem(i);
                    switch (menu.getItemId()) {
                        case R.id.i_home:
                            menu.setIcon(R.mipmap.ic_home_1);
                            break;
                        case R.id.i_category:
                            menu.setIcon(R.mipmap.ic_home_2);
                            break;
                        case R.id.i_msg:
                            menu.setIcon(R.mipmap.ic_home_3);
                            break;
                        case R.id.i_cart:
                            menu.setIcon(R.mipmap.ic_home_4);
                            break;
                    }
                }
                switch (item.getItemId()) {
                    case R.id.i_home:
                        item.setIcon(R.mipmap.ic_home_1_selected);
                        break;
                    case R.id.i_category:
                        item.setIcon(R.mipmap.ic_home_2_selected);
                        break;
                    case R.id.i_msg:
                        item.setIcon(R.mipmap.ic_home_3_selected);
                        break;
                    case R.id.i_cart:
                        item.setIcon(R.mipmap.ic_home_4_selected);
                        break;
                }
                return true;
            }
        });
        MenuItem menu = bnve.getMenu().getItem(0);
        menu.setIcon(R.mipmap.ic_home_1_selected);

        adapter = new VpAdapter(getSupportFragmentManager());
        vp.setOffscreenPageLimit(4);
        vp.setAdapter(adapter);
        bnve.setupWithViewPager(vp);
        //设置从导航页跳转到指定页
        bnve.setSelectedItemId(bnve.getMenu().getItem(guidId).getItemId());
//        bnve.getBottomNavigationMenuView().removeViewAt(3);
//        FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) bnve.getBottomNavigationMenuView().getLayoutParams();
//        params.width = ScreenUtils.getScreenWidth() * 4 / 3;
//        bnve.getBottomNavigationMenuView().setLayoutParams(params);

//        String mall_switch=Arad.preferences.getString(Config.MALL_SWITCH);
//        if(!TextUtils.isEmpty(mall_switch)){
//            int mallSwitch=0;
            if(Global.IS_SHOW == 0){
                bnve.getBottomNavigationMenuView().removeViewAt(2);
                FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) bnve.getBottomNavigationMenuView().getLayoutParams();
                params.width = ScreenUtils.getScreenWidth() * 4 / 3;
                bnve.getBottomNavigationMenuView().setLayoutParams(params);
            }
//        }

        vp.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(final int position) {
                if (position == 0) {
                    adapter.getItem(0).onHiddenChanged(false);
                } else {
                    adapter.getItem(0).onHiddenChanged(true);
                }

//                if (position == 3 && MyApp.settings.getMall_switch() == 0) {
//                    final NormalDialog dialog = new NormalDialog(MainActivity.this);
//                    dialog.style(NormalDialog.STYLE_TWO);
//                    dialog.content("敬请期待");
//                    dialog.btnNum(1);
//                    dialog.btnText("确定");
//                    dialog.setCancelable(false);
//                    dialog.setCanceledOnTouchOutside(false);
//                    dialog.setOnBtnClickL(new OnBtnClickL() {
//                        @Override
//                        public void onBtnClick() {
//                            dialog.dismiss();
//                            vp.setCurrentItem(mPreTabIndex, false);
//                        }
//                    });
//                    dialog.show();
//                } else {
                mPreTabIndex = position;
//                }
            }
        });

        Arad.bus.register(this);
        updateUtil = new UpdateUtil(MainActivity.this);
        int vCode= PackageUtils.getVersionCode(MainActivity.this);
//                ToastUtils.showShort("已是最新版本");
//        auto_update(AppUtils.getAppVersionName());

    }
    private Disposable auto_update(String vCode) {
        return APIRetrofit.getDefault().checkUpgrade(Global.HEADER,"1",vCode)
                .compose(RxUtil.<BaseResult2<VersionInfo>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<VersionInfo>>() {
                    @Override
                    public void accept(BaseResult2<VersionInfo> result2) throws Exception {
                        if(result2.isSuccess()){
                            if(null==result2.getData().getVersion()){
//                                ToastUtils.showShort("已是最新版本");
                                return;
                            }
                            Logg.e("==数据库版本号=="+result2.getData().getVersion());
                            int versionCode=Integer.valueOf(result2.getData().getVersion().replace(".",""));
//                            int vcode= PackageUtils.getVersionCode(AboutUsActivity.this);
                            int vcode=Integer.valueOf(vCode.replace(".",""));
                            Logg.e("====版本号===="+versionCode+"=="+vcode);
                            if(versionCode<=vcode){
//                                ToastUtils.showShort("已是最新版本");
                            }else{
                                showUpdateDialog(result2.getData().getAppfile(),result2.getData().getContent());
                            }
                        } else{
                            ToastUtils.showShort(result2.getMsg());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
//                        hideProgress();
//                        throwable.printStackTrace();
//                        ToastUtils.showShort("已是最新版本");
                    }
                });
    }
    private void showUpdateDialog(String appurl,String content){
        updateUtil.setOnUpdateStatusChangeListener(null)
                .showDownloadNotification("正在更新", "正在下载UpdateV3框架更新...")
                .showDownloadProgressDialog("正在下载", "", "取消")
                .start(appurl,
                        "发现新版本",
                        content,
                        "去更新",
                        "再想想",
                        "",
                        false
                );
    }
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (null != intent){
            guidId = intent.getIntExtra("guid_id",0);
            vp.setCurrentItem(guidId);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGetMsg(EventModel ev) {
        if (ev.getEventCode() == 20101651) {
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (Arad.bus.isRegistered(this)) {
            Arad.bus.unregister(this);
        }
    }

    private class VpAdapter extends FragmentPagerAdapter {

        public VpAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            if (position == 0) {// 课程中心
                return Home1Fragment.newInstance();
            } else if (position == 1) {// 直播
                return Home2Fragment.newInstance();
            } else if (position == 2) {// 商城
                return Home3Fragment.newInstance();
            } else if (position == 3) {// 我的
                return Home4Fragment.newInstance();
            }

            return Home2Fragment.newInstance();
        }

        @Override
        public int getCount() {
            return 4;
        }
    }
    private long waitTime = 2000;
    private long touchTime = 0;
//    @Override
//    public void onBackPressed() {
//        super.onBackPressed();
//        if(Global.IS_SHOW ==0){
//            long currentTime = System.currentTimeMillis();
//            if ((currentTime - touchTime) >= waitTime) {
//                ToastUtils.showShortSafe("再按一次退出程序");
//                touchTime = currentTime;
//            } else {
//                super.onBackPressed();
//            }
//        }else{
//            startActivity(GuidActivity.class);
//        }
//
//    }
    private long mExitTime;
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //判断用户是否点击了“返回键”
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if(Global.IS_SHOW ==0){
                //与上次点击返回键时刻作差
                if ((System.currentTimeMillis() - mExitTime) > 2000) {
                    //大于2000ms则认为是误操作，使用Toast进行提示
                    ToastUtils.showShortSafe("再按一次退出程序");
                    //并记录下本次点击“返回键”的时刻，以便下次进行判断
                    mExitTime = System.currentTimeMillis();
                } else {
                    //小于2000ms则认为是用户确实希望退出程序-调用System.exit()方法进行退出
                    System.exit(0);
                }
            }else if(Global.IS_SHOW ==1){
                startActivity(GuidActivity.class);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}